<template>
  <div class="change-password">
    <h2>修改密码</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- <el-form-item label="当前密码" prop="currentPassword">
        <el-input v-model="form.currentPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">修改密码</el-button>
      </el-form-item> -->

      <el-form-item label="手机号" prop="inputMobile">
        <el-input v-model="form.inputMobile"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="Verificationcode">
        <!-- <el-input v-model="form.Verificationcode" ></el-input> -->
        <div style="width: 100%;">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-input v-model="form.Verificationcode" placeholder="请输入您的验证码" ref="verificationInput" />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="Getverificationcode('resetpwd')">获取验证码</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">修改密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { IHuoQuJiFenModel, IHuoQuJiFenData, ICheckUserNameResult, GetBaseURL } from '../../composables/types';
import { setCookie, getCookie } from '../../composables/utils';

// 接口地址
const baseUrl: string = GetBaseURL();
//const baseUrl: string = "https://api.bishi.turuio.net"; //测试

const formRef = ref<FormInstance>();

const form = reactive({
  // 手机号
  inputMobile: '',
  // 验证码
  Verificationcode: '',
  currentPassword: '',
  // 新密码
  newPassword: '',
  confirmPassword: ''

});

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (form.confirmPassword !== '') {
      if (!formRef.value) return;
      formRef.value.validateField('confirmPassword', () => { });
    }
    callback();
  }
};

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== form.newPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const rules = reactive<FormRules>({
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [{ validator: validatePass, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePass2, trigger: 'blur' }]
});

// 修改密码
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      resetPassword().then(result => {
        const checkResult = result;
        if (result.data === undefined || checkResult === null) {
          errorMessge("密码修改失败");
          return;
        }
        if (checkResult.code === 1) {
          successMessge(checkResult.msg);  //密码修改成功
        } else {
          errorMessge(checkResult.msg); //密码修改失败
        }
      })
        .catch(error => {
          console.log('error', error);
          errorMessge("密码修改失败");
        });
    } else {
      console.log('error submit!');
    }
  });
};

///成功提示
const successMessge = (value: string) => {
  ElMessage({
    message: value,
    type: 'success',
  })
}
//错误提示
const errorMessge = (value: string) => {
  ElMessage.error(value)
}

// 获取验证码
const Getverificationcode = async (eventName: string) => {
  // successMessge("获取验证码");
  let checkResult: ICheckUserNameResult;
  checkResult = await sendSMSCommand(eventName);
  if (checkResult == null || checkResult == undefined) {
    errorMessge('短信发送失败');  //短信发送失败
    return;
  }
  else if (checkResult.code == 1) {
    successMessge(checkResult.msg);  //短信已发送
  }
  else {
    errorMessge(checkResult.msg);  //短信发送失败
  }
};


/**
 * 发送短信命令
 * @param eventName 事件名称，用于区分发送短信的场景
 * @returns {Promise<ICheckUserNameResult>} 返回一个Promise，包含用户名检查结果
 */
async function sendSMSCommand(eventName: string) {
  let checkResult: ICheckUserNameResult;
  // 构造请求数据，包含手机号和事件名称
  const data = { mobile: form.inputMobile, event: eventName };
  try {
    // 发起发送短信的请求
    const response = await axios.post(`${baseUrl}/api/sms/send`, data);
    // 解析响应数据
    checkResult = response.data;
    return checkResult;
  } catch (error) {
    // 处理异常情况，设置检查结果码和消息
    checkResult = { code: -1, msg: "获取验证码报错," + error, time: "", data: null };
    throw error; // 或者根据业务逻辑处理错误
  }
}

/**
 * 异步函数：检查SMS验证码是否有效
 * @param eventName - 事件名称，用于区分不同场景的验证码验证,如：mobilelogin
 * @returns 返回一个Promise，包含验证结果对象ICheckUserNameResult
 * 
 * 此函数通过axios库发送POST请求到后端服务，以检验提供的SMS验证码是否有效
 * 它使用mobile（用户手机号）、event（事件名称）和captcha（验证码）作为请求参数
 * 如果服务器响应成功，它将返回验证结果；如果发生错误，它将处理错误并抛出异常
 */
async function checkSMSCode(eventName: string): Promise<ICheckUserNameResult> {
  let checkResult: ICheckUserNameResult;
  // 准备请求数据，包括用户手机号、事件名称和用户输入的验证码
  const data = { mobile: form.inputMobile, event: eventName, captcha: form.Verificationcode };
  try {
    // 发送POST请求到后端API地址，检查验证码有效性
    const response = await axios.post(`${baseUrl}/api/sms/check`, data);
    // 解析响应数据作为验证结果
    checkResult = response.data;
    return checkResult;
  } catch (error) {
    // 在捕获到错误时，设置验证结果的code为-1，并添加错误信息
    checkResult = { code: -1, msg: "检验验证码是否有效报错," + error, time: "", data: null };
    throw error; // 或者根据业务逻辑处理错误
  }
}

/**
 * 异步函数用于重置用户密码
 * 
 * 该函数的主要作用是通过发送请求到后端服务器，以重置用户密码
 * 它首先构造一个包含用户信息的对象，然后使用axios库发送POST请求
 * 如果请求成功，它会解析后端返回的数据，并将其作为结果返回
 * 如果在请求过程中出现错误，它会捕获错误，并抛出以便进一步处理
 * 
 * @returns {Promise<ICheckUserNameResult>} 返回一个Promise对象，该对象解析为包含检查结果的ICheckUserNameResult类型
 */
async function resetPassword(): Promise<ICheckUserNameResult> {
  // 用于存储用户名检查结果的对象
  let checkResult: ICheckUserNameResult;
  // 从cookie中获取存储的用户邮箱
  let email = getCookie('TR_email');

  //验证码是否正确
  checkResult = await checkSMSCode("resetpwd");
  if (checkResult.code != 1) {
    //验证码不正确
    return checkResult;
  }

  if (email == null || email == '' || email == undefined) {
    //没有邮箱，用手机号编一个
    email = form.inputMobile + '@QQ.com';
  }
  // 构造包含用户手机号、新密码、邮箱、验证码等信息的对象
  const data = { mobile: form.inputMobile, newpassword: form.newPassword, email: email, captcha: form.Verificationcode, type: "mobile" };

  try {
    // 向后端发送注册请求
    const response = await axios.post(`${baseUrl}/api/user/resetpwd`, data);
    // 解析并返回登录结果
    checkResult = response.data;
    return checkResult;
  } catch (error) {
    // 异常情况下构造错误的登录结果对象
    checkResult = { code: -1, msg: "修改密码报错," + error, time: "", data: null };
    // 抛出错误以便进一步处理
    throw error; // 或者根据业务逻辑处理错误
  }
}

</script>
